import os
import sys
import logging
import asyncio
from typing import Dict, Any

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from dotenv import load_dotenv
load_dotenv()

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger('shopify_diagnostic')

try:
    import shopify
except ImportError:
    logger.error("❌ 未安装Shopify API库，请运行: pip install shopifyapi")
    sys.exit(1)


def check_env_variables() -> Dict[str, Any]:
    """检查Shopify环境变量配置"""
    logger.info("\n=== 环境变量检查 ===")
    
    required_vars = {
        "SHOPIFY_API_KEY": os.getenv("SHOPIFY_API_KEY", ""),
        "SHOPIFY_API_SECRET": os.getenv("SHOPIFY_API_SECRET", ""),
        "SHOPIFY_STORE_URL": os.getenv("SHOPIFY_STORE_URL", ""),
        "SHOPIFY_ACCESS_TOKEN": os.getenv("SHOPIFY_ACCESS_TOKEN", "")
    }
    
    missing_vars = [var for var, value in required_vars.items() if not value]
    format_issues = []
    
    # 检查URL格式
    store_url = required_vars["SHOPIFY_STORE_URL"]
    if store_url and not store_url.endswith('.myshopify.com'):
        format_issues.append(f"SHOPIFY_STORE_URL格式不正确: {store_url}，应类似于 'your-store.myshopify.com'")
    
    # 检查强制模拟模式
    force_mock_mode = os.getenv("SHOPIFY_FORCE_MOCK_MODE", "false").lower() == "true"
    
    # 输出检查结果
    logger.info(f"强制模拟模式: {'✅ 已启用' if force_mock_mode else '❌ 未启用'}")
    
    for var_name, value in required_vars.items():
        status = "✅ 已配置" if value else "❌ 未配置"
        # 显示部分值用于调试，不显示完整敏感信息
        display_value = f"{value[:5]}..." if value and len(value) > 5 else value
        logger.info(f"{var_name}: {status} {'(' + display_value + ')' if value else ''}")
    
    for issue in format_issues:
        logger.warning(f"⚠️ {issue}")
    
    return {
        "required_vars": required_vars,
        "missing_vars": missing_vars,
        "format_issues": format_issues,
        "force_mock_mode": force_mock_mode,
        "config_complete": len(missing_vars) == 0 and len(format_issues) == 0
    }


def test_api_versions(required_vars: Dict[str, str]) -> Dict[str, Any]:
    """测试不同的Shopify API版本"""
    logger.info("\n=== API版本兼容性测试 ===")
    
    test_results = {
        "versions": [],
        "success": False,
        "best_version": None
    }
    
    # 测试的API版本列表
    api_versions = [
        "2025-01",  # 最新版本
        "2024-10",
        "2024-07",
        "2024-04",
        "2023-10",
        "2023-07",
        "2023-04"
    ]
    
    for version in api_versions:
        try:
            logger.info(f"测试API版本: {version}")
            
            # 设置会话
            shopify.Session.setup(api_key=required_vars["SHOPIFY_API_KEY"], 
                                 secret=required_vars["SHOPIFY_API_SECRET"])
            
            # 创建会话
            session = shopify.Session(required_vars["SHOPIFY_STORE_URL"], 
                                     version, 
                                     required_vars["SHOPIFY_ACCESS_TOKEN"])
            
            # 激活会话
            shopify.ShopifyResource.activate_session(session)
            
            # 测试连接 - 获取商店信息
            shop = shopify.Shop.current()
            logger.info(f"  ✅ 成功连接 (版本 {version})")
            logger.info(f"  - 商店名称: {shop.name}")
            logger.info(f"  - 商店URL: {shop.myshopify_domain}")
            
            test_results["versions"].append({
                "version": version,
                "success": True,
                "shop_name": shop.name
            })
            
            # 保存第一个成功的版本
            if not test_results["best_version"]:
                test_results["best_version"] = version
                test_results["success"] = True
                
            # 清理会话
            shopify.ShopifyResource.clear_session()
            
        except Exception as e:
            error_type = type(e).__name__
            logger.warning(f"  ❌ 连接失败 (版本 {version}): {error_type} - {str(e)}")
            
            # 保存失败信息
            test_results["versions"].append({
                "version": version,
                "success": False,
                "error": str(e),
                "error_type": error_type
            })
            
            # 清理会话
            try:
                shopify.ShopifyResource.clear_session()
            except:
                pass
    
    return test_results


def test_product_access(required_vars: Dict[str, str], best_version: str) -> Dict[str, Any]:
    """测试产品访问权限"""
    logger.info("\n=== 产品访问权限测试 ===")
    
    if not best_version:
        logger.warning("❌ 无法测试产品访问权限：没有找到可用的API版本")
        return {"success": False, "error": "没有可用的API版本"}
    
    try:
        # 设置会话
        shopify.Session.setup(api_key=required_vars["SHOPIFY_API_KEY"], 
                             secret=required_vars["SHOPIFY_API_SECRET"])
        
        # 创建会话
        session = shopify.Session(required_vars["SHOPIFY_STORE_URL"], 
                                 best_version, 
                                 required_vars["SHOPIFY_ACCESS_TOKEN"])
        
        # 激活会话
        shopify.ShopifyResource.activate_session(session)
        
        # 尝试获取产品列表
        logger.info("尝试获取产品列表...")
        products = shopify.Product.find(limit=3)
        
        logger.info(f"✅ 成功获取到 {len(products)} 个产品")
        for i, product in enumerate(products[:2]):
            logger.info(f"  - 产品 {i+1}: {product.title} (ID: {product.id})")
        
        # 清理会话
        shopify.ShopifyResource.clear_session()
        
        return {
            "success": True,
            "product_count": len(products),
            "has_products": len(products) > 0
        }
        
    except Exception as e:
        error_type = type(e).__name__
        logger.error(f"❌ 产品访问失败: {error_type} - {str(e)}")
        
        # 特别处理403错误
        if "403" in str(e) or "Forbidden" in str(e).lower():
            logger.warning("⚠️ 权限错误：访问令牌可能缺少必要的读取产品权限")
        
        # 清理会话
        try:
            shopify.ShopifyResource.clear_session()
        except:
            pass
        
        return {
            "success": False,
            "error": str(e),
            "error_type": error_type
        }


def test_order_access(required_vars: Dict[str, str], best_version: str) -> Dict[str, Any]:
    """测试订单访问权限"""
    logger.info("\n=== 订单访问权限测试 ===")
    
    if not best_version:
        logger.warning("❌ 无法测试订单访问权限：没有找到可用的API版本")
        return {"success": False, "error": "没有可用的API版本"}
    
    try:
        # 设置会话
        shopify.Session.setup(api_key=required_vars["SHOPIFY_API_KEY"], 
                             secret=required_vars["SHOPIFY_API_SECRET"])
        
        # 创建会话
        session = shopify.Session(required_vars["SHOPIFY_STORE_URL"], 
                                 best_version, 
                                 required_vars["SHOPIFY_ACCESS_TOKEN"])
        
        # 激活会话
        shopify.ShopifyResource.activate_session(session)
        
        # 尝试获取订单列表
        logger.info("尝试获取订单列表...")
        orders = shopify.Order.find(limit=3, status="any")
        
        logger.info(f"✅ 成功获取到 {len(orders)} 个订单")
        for i, order in enumerate(orders[:2]):
            logger.info(f"  - 订单 {i+1}: {order.name} (ID: {order.id}, 状态: {order.financial_status})")
        
        # 清理会话
        shopify.ShopifyResource.clear_session()
        
        return {
            "success": True,
            "order_count": len(orders),
            "has_orders": len(orders) > 0
        }
        
    except Exception as e:
        error_type = type(e).__name__
        logger.error(f"❌ 订单访问失败: {error_type} - {str(e)}")
        
        # 特别处理403错误
        if "403" in str(e) or "Forbidden" in str(e).lower():
            logger.warning("⚠️ 权限错误：访问令牌可能缺少必要的读取订单权限")
        
        # 清理会话
        try:
            shopify.ShopifyResource.clear_session()
        except:
            pass
        
        return {
            "success": False,
            "error": str(e),
            "error_type": error_type
        }


def generate_fix_recommendations(env_check: Dict[str, Any], 
                               api_test: Dict[str, Any],
                               product_test: Dict[str, Any],
                               order_test: Dict[str, Any]) -> None:
    """生成修复建议"""
    logger.info("\n=== 问题分析与修复建议 ===")
    
    recommendations = []
    
    # 环境变量问题
    if env_check["missing_vars"]:
        recommendations.append(
            f"1. 请在.env文件中配置缺失的环境变量: {', '.join(env_check['missing_vars'])}"
        )
    
    # URL格式问题
    if env_check["format_issues"]:
        recommendations.append(
            "2. 请修正SHOPIFY_STORE_URL格式，确保它以'.myshopify.com'结尾"
        )
    
    # API版本问题
    if not api_test["success"]:
        recommendations.append(
            "3. 所有API版本测试失败，请检查API凭据是否正确"
        )
    
    # 权限问题
    permission_issues = []
    if product_test.get("error_type") == "ForbiddenError" or "403" in str(product_test.get("error", "")):
        permission_issues.append("读取产品权限")
    
    if order_test.get("error_type") == "ForbiddenError" or "403" in str(order_test.get("error", "")):
        permission_issues.append("读取订单权限")
    
    if permission_issues:
        recommendations.append(
            f"4. 访问令牌缺少必要权限: {', '.join(permission_issues)}。请在Shopify后台重新生成带有正确权限的访问令牌"
        )
    
    # 临时解决方案
    if not env_check["force_mock_mode"]:
        recommendations.append(
            "5. 临时解决方案：设置环境变量SHOPIFY_FORCE_MOCK_MODE=true以使用模拟数据模式"
        )
    
    # 总结和建议
    if recommendations:
        logger.info("检测到以下问题并提供修复建议:")
        for rec in recommendations:
            logger.info(f"   {rec}")
        
        logger.info("\n详细修复步骤:")
        logger.info("1. 打开.env文件")
        logger.info("2. 检查并修正以下配置:")
        logger.info("   SHOPIFY_API_KEY=your_api_key")
        logger.info("   SHOPIFY_API_SECRET=your_api_secret")
        logger.info("   SHOPIFY_STORE_URL=your-store.myshopify.com")
        logger.info("   SHOPIFY_ACCESS_TOKEN=your_access_token")
        logger.info("3. 确保Shopify应用在Shopify后台有正确的权限配置")
        logger.info("4. 重启服务器以应用更改")
        
        if not api_test["success"] and not env_check["force_mock_mode"]:
            logger.info("\n临时解决方案 - 使用模拟数据:")
            logger.info("在.env文件中添加: SHOPIFY_FORCE_MOCK_MODE=true")
            logger.info("这将允许系统使用模拟数据运行，即使Shopify API连接失败")
    else:
        logger.info("✅ 未检测到明显问题！")
        
        if api_test["success"]:
            logger.info(f"\n推荐使用API版本: {api_test['best_version']}")
            
            if product_test.get("success"):
                logger.info(f"✅ 产品访问正常 (找到 {product_test['product_count']} 个产品)")
            else:
                logger.warning("⚠️ 产品访问可能存在问题")
                
            if order_test.get("success"):
                logger.info(f"✅ 订单访问正常 (找到 {order_test['order_count']} 个订单)")
            else:
                logger.warning("⚠️ 订单访问可能存在问题")
        
        if env_check["force_mock_mode"]:
            logger.info("\n⚠️ 注意：当前启用了强制模拟数据模式")
            logger.info("如果API连接已经正常，请移除SHOPIFY_FORCE_MOCK_MODE=true环境变量以使用真实数据")


def test_mock_data_availability() -> None:
    """测试模拟数据模块是否正常"""
    logger.info("\n=== 模拟数据可用性测试 ===")
    
    try:
        from services.shopify_api_mock import get_mock_products, get_mock_orders
        
        mock_products = get_mock_products()
        mock_orders = get_mock_orders()
        
        logger.info(f"✅ 成功加载模拟数据模块")
        logger.info(f"  - 模拟产品数量: {len(mock_products)}")
        logger.info(f"  - 模拟订单数量: {len(mock_orders)}")
        
        if mock_products:
            logger.info(f"  示例产品: {mock_products[0].get('title', 'N/A')}")
        if mock_orders:
            logger.info(f"  示例订单: {mock_orders[0].get('name', 'N/A')}")
            
    except Exception as e:
        logger.error(f"❌ 模拟数据模块加载失败: {e}")


async def main():
    """主诊断函数"""
    logger.info("\n==========================================")
    logger.info("Shopify API连接综合诊断工具")
    logger.info("==========================================")
    
    # 1. 检查环境变量
    env_check = check_env_variables()
    
    # 2. 测试API版本兼容性
    api_test = {"success": False, "versions": [], "best_version": None}
    product_test = {"success": False}
    order_test = {"success": False}
    
    if env_check["config_complete"] and not env_check["force_mock_mode"]:
        # 只有在配置完整且未强制模拟模式时才测试实际API连接
        api_test = test_api_versions(env_check["required_vars"])
        
        if api_test["success"]:
            # 测试产品访问
            product_test = test_product_access(env_check["required_vars"], api_test["best_version"])
            # 测试订单访问
            order_test = test_order_access(env_check["required_vars"], api_test["best_version"])
    elif env_check["force_mock_mode"]:
        logger.info("\n⚠️ 检测到强制模拟模式已启用，跳过实际API连接测试")
    
    # 3. 测试模拟数据
    test_mock_data_availability()
    
    # 4. 生成修复建议
    generate_fix_recommendations(env_check, api_test, product_test, order_test)
    
    logger.info("\n==========================================")
    logger.info("诊断完成！")
    logger.info("==========================================")


if __name__ == "__main__":
    asyncio.run(main())